package com.naxiang.zhaohang.naxiangadressselect;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.naxiang.zhaohang.been.GetJsonDataUtil;
import com.naxiang.zhaohang.been.JsonBean;
import com.naxiang.zhaohang.passworld.PayPwdEditText;
import com.naxiang.zhaohang.pickerview.builder.OptionsPickerBuilder;
import com.naxiang.zhaohang.pickerview.builder.TimePickerBuilder;
import com.naxiang.zhaohang.pickerview.listener.OnOptionsSelectListener;
import com.naxiang.zhaohang.pickerview.listener.OnTimeSelectChangeListener;
import com.naxiang.zhaohang.pickerview.listener.OnTimeSelectListener;
import com.naxiang.zhaohang.pickerview.view.OptionsPickerView;
import com.naxiang.zhaohang.pickerview.view.TimePickerView;

import com.naxiang.zhaohang.weight.NiceSpinner;
import com.uzmap.pkg.uzcore.UZWebView;
import com.uzmap.pkg.uzcore.uzmodule.UZModule;
import com.uzmap.pkg.uzcore.uzmodule.UZModuleContext;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 作者: 赵航
 * 创建时间: 2018/5/30 13:07
 * 描述:
 */
public class NaXiangAdressSelectActivity extends UZModule {

    private ArrayList<JsonBean>                     options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>>            options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private static final int MSG_LOAD_DATA    = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED  = 0x0003;

    private Thread mThread;
    private boolean isLoaded = false;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (mThread == null) {//如果已创建就不再重新创建子线程了
                        mThread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        mThread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    //                   Toast.makeText(getContext(), "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;

                    shownSelect();

                    break;

                case MSG_LOAD_FAILED:
                    //                   Toast.makeText(getContext(), "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;

            }


        }
    };
    private UZModuleContext mModuleCity;
    private TimePickerView  pvTime;
    private UZModuleContext mModuleContext;
    private NiceSpinner     mNiceSpinner;
    private List<String> mDataListBeen;
    private List<String> mDataList;
    private boolean         mOutDlade;
    private double          mPadding;
    private int             mTextSize;
    private int             mTitleSize;
    private UZModuleContext mModuleItms;
    private String          mTitleText;
    private String          mCancel;
    private String          mSure;
    private String          mTitlecolor;
    private String          mSubmitcolor;
    private String          mCancelcolor;
    private String          mTitlebgcolor;
    private String          mBgcolore;
    private String          mDividercolor;
    private String          mTextcolorcenter;
    private int             mShwonNuber;
    private float mShadowColor=0.7f;
    private PayPwdEditText mPayPwdEditText;
    private String mPassword="";
    private Dialog mDialogPassword;

    //显示地址选择框
    private void shownSelect() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(getContext(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
                JSONObject object = new JSONObject();
                try {
                    object.put("address", tx);
                    object.put("province", options1Items.get(options1).getPickerViewText());
                    object.put("city", options2Items.get(options1).get(options2));
                    object.put("county", options3Items.get(options1).get(options2).get(options3));
                    object.put("provinceId", options1);
                    object.put("cityId", options2);
                    object.put("countyId", options3);
                    mModuleCity.success(object, true);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        })

                .setCancelText(mCancel)//取消按钮文字
                .setSubmitText(mSure)//确认按钮文字
                .setTitleText(mTitleText)//标题文字
                .setDividerColor(Color.parseColor(mDividercolor))
                .setTextColorCenter(Color.parseColor(mTextcolorcenter)) //设置选中项文字颜色
                .setTitleSize(mTitleSize)//标题文字大小
                .setOutSideCancelable(mOutDlade)//点击外部是否取消
                .setContentTextSize(mTextSize)//滚轮文字的大小
                .setLineSpacingMultiplier((float) mPadding)//设置两线之间的距离
                .setTitleColor(Color.parseColor(mTitlecolor))//标题文字颜色
                .setSubmitColor(Color.parseColor(mSubmitcolor))//确定按钮文字颜色
                .setCancelColor(Color.parseColor(mCancelcolor))//取消按钮文字颜色
                .setTitleBgColor(Color.parseColor(mTitlebgcolor))//标题背景颜色 Night mode
                .setBgColor(Color.parseColor(mBgcolore))//滚轮背景颜色 Night mode
                .build();

                    /*pvOptions.setPicker(options1Items);//一级选择器
                    pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();

    }

    public NaXiangAdressSelectActivity(UZWebView webView) {
        super(webView);
    }

    //打开地理选择器
    public void jsmethod_openNaxiangCity(UZModuleContext moduleContext) {

        mModuleCity = moduleContext;
        mOutDlade = moduleContext.optBoolean("maskswitch", true);
        mPadding = moduleContext.optDouble("padding", 1.5);
        mTextSize = moduleContext.optInt("textSize", 18);
        mTitleSize = moduleContext.optInt("mTitleSize", 20);
        mTitleText = moduleContext.optString("titleText", "城市选择");
        mCancel = moduleContext.optString("cancel", "取消");
        mSure = moduleContext.optString("sure", "确定");
        mTitlecolor = moduleContext.optString("titlecolor", "#000000");
        mSubmitcolor = moduleContext.optString("submitcolor", "#1919FF");
        mCancelcolor = moduleContext.optString("cancelcolor", "#1919FF");
        mTitlebgcolor = moduleContext.optString("titlebgcolor", "#F5F5F5");
        mBgcolore = moduleContext.optString("bgcolor", "#FFFFFF");
        mDividercolor = moduleContext.optString("dividercolor", "#000000");
        mTextcolorcenter = moduleContext.optString("textcolorcenter", "#000000");
        mShadowColor=(float) moduleContext.optDouble("shadowColor", 0.7f);
        if (!isLoaded) {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        } else {
            shownSelect();
        }
    }


    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(getContext(), "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();

        try {
            JSONArray data = new JSONArray(result);
            for (int i = 0; i < data.length(); i++) {
//                JsonBean entity = GsonUtil.parseJsonToBean(data.optJSONObject(i).toString(), JsonBean.class);
                //获取市的名称
                String mProviceName = (String) data.optJSONObject(i).optString("name");
                String cityListName = (String) data.optJSONObject(i).optString("city");
                JSONArray jsonArray = new JSONArray(cityListName);

                List<JsonBean.CityBean> cityName = new ArrayList<>();
                for (int j=0;j<jsonArray.length();j++){
                    JSONObject jsonObject = jsonArray.getJSONObject(j);
                    if (jsonObject!=null){
                        //获取市的名字
                        String mCityName = jsonObject.optString("name");
                        //获取乡的名称
                        String areaName = jsonObject.optString("area");
                        //再次解析集合
                        JSONArray areaArray = new JSONArray(areaName);
                        List<String> countryName = new ArrayList<>();
                        for (int k=0;k<areaArray.length();k++){
                            String mCountry = (String) areaArray.opt(k);
                            countryName.add(mCountry);
                        }
                        JsonBean.CityBean cityBean = new JsonBean.CityBean(mCityName, countryName);
                        cityName.add(cityBean);
                    }
                }

                JsonBean bean = new JsonBean(mProviceName, cityName);
                detail.add(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    //打开时间选择器
    public void jsmethod_openNaxiangDate(UZModuleContext moduleContext) {
        initTimePicker(moduleContext);
        mModuleContext = moduleContext;

    }

    /**
     * 时间转换
     *
     * @return
     */
    private String getTime(Date date) {//可根据需要自行截取数据显示
        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    private void initTimePicker(UZModuleContext moduleContext) {

        int mStartYear = moduleContext.optInt("startYear", 2010);
        int mEndYear = moduleContext.optInt("endYear", 2020);
        int mStartMonth = moduleContext.optInt("startMonth", 9);
        int mEndMonth = moduleContext.optInt("endMonth", 1);
        int mStartDay = moduleContext.optInt("startDay", 1);
        int mEndDay = moduleContext.optInt("endDay", 1);

        //点击外部是否可以消失,false为不可以消失，ture为可以消失,默认为ture
        boolean mOutDlade = moduleContext.optBoolean("maskswitch", false);
        //点击滚轮是否可以循环,false为不可以循环，ture为可以循环,默认为ture
        boolean mIsCycle = moduleContext.optBoolean("isCycle", false);
        //为上下条目之间的距离，滚轮间距设置（1.2-2.0倍，此为文字高度的间距倍数）;
        double mPadding = moduleContext.optDouble("padding", 1.5);
        //为滚轮的选择文字的大小，默认为18ps；
        int mTextSize = moduleContext.optInt("textSize", 18);
        //为标题文字的大小
        int mTitleSize = moduleContext.optInt("titleSize", 20);
        String mTitleText = moduleContext.optString("titleText", "时间选择器");
        String mCancel = moduleContext.optString("cancel", "取消");
        String mSure = moduleContext.optString("sure", "确定");
        String mTitlecolor = moduleContext.optString("titlecolor", "#000000");
        String mSubmitcolor = moduleContext.optString("submitcolor", "#1919FF");
        String mCancelcolor = moduleContext.optString("cancelcolor", "#1919FF");
        String mTitlebgcolor = moduleContext.optString("titlebgcolor", "#F5F5F5");
        String mBgcolore = moduleContext.optString("bgcolor", "#FFFFFF");
        String mTextcolorcenter = moduleContext.optString("textcolorcenter", "#000000");

        //默认时间
        int mDefaultYear = moduleContext.optInt("defaultYear", 2018);
        int mDefaultMoth = moduleContext.optInt("defaultMoth", 1);
        int mDefaultDay = moduleContext.optInt("defaultDay", 1);
        int mDefaultHour = moduleContext.optInt("defaultHour", 1);
        int mDefaultMin = moduleContext.optInt("defaultMin", 1);
        int mDefaultSecond = moduleContext.optInt("defaultSecond", 1);
        Calendar selectedDate = Calendar.getInstance();

        selectedDate.set(mDefaultYear, mDefaultMoth - 1, mDefaultDay, mDefaultHour, mDefaultMin, mDefaultSecond);
        //显示设置
        boolean mShowYear = moduleContext.optBoolean("showYear", true);
        boolean mShowMoth = moduleContext.optBoolean("showMoth", true);
        boolean mShowDay = moduleContext.optBoolean("showDay", true);
        boolean mShowHour = moduleContext.optBoolean("showHour", true);
        boolean mShowMin = moduleContext.optBoolean("showMin", true);
        boolean mShowSecond = moduleContext.optBoolean("showSecond", true);

        Calendar startDate = Calendar.getInstance();
        startDate.set(mStartYear, mStartMonth - 1, mStartDay);
        Calendar endDate = Calendar.getInstance();
        endDate.set(mEndYear, mEndMonth - 1, mEndDay);

        pvTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String time = getTime(date);

                String[] split = time.split(" ");
                String mTimeData = split[0];
                String mMinsData = split[1];

                String[] mYearData = mTimeData.split("-");
                String mYear = mYearData[0];
                String mMoth = mYearData[1];
                String mDay = mYearData[2];

                String[] mMinit = mMinsData.split(":");
                String mHour = mMinit[0];
                String mMin = mMinit[0];
                String mSecond = mMinit[0];

                System.out.println(mYear + "==" + mMoth + "==" + mDay + "==" + mHour + "==" + mMin + "==" + mSecond);
                JSONObject object = new JSONObject();
                try {
                    object.put("yearData", mTimeData);
                    object.put("hourData", mMinsData);
                    object.put("time", time);
                    object.put("year", mYear);
                    object.put("moth", mMoth);
                    object.put("day", mDay);
                    object.put("hour", mHour);
                    object.put("min", mMin);
                    object.put("second", mSecond);
                    mModuleContext.success(object, true);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {

                    }
                })
                .setType(new boolean[]{mShowYear, mShowMoth, mShowDay, mShowHour, mShowMin, mShowSecond})
                .isDialog(true)
                .setCancelText(mCancel)//取消按钮文字
                .setSubmitText(mSure)//确认按钮文字
                .setTitleText(mTitleText)//标题文字
                .setTitleSize(mTitleSize)//标题文字大小
                .setTextColorCenter(Color.parseColor(mTextcolorcenter))
                .setOutSideCancelable(mOutDlade)//点击外部是否取消
                .isCyclic(mIsCycle)//是否循环滚动
                .setContentTextSize(mTextSize)
                .setLineSpacingMultiplier((float) mPadding)//设置两线之间的距离
                .setRangDate(startDate, endDate)
                .setTitleColor(Color.parseColor(mTitlecolor))//标题文字颜色
                .setSubmitColor(Color.parseColor(mSubmitcolor))//确定按钮文字颜色
                .setCancelColor(Color.parseColor(mCancelcolor))//取消按钮文字颜色
                .setTitleBgColor(Color.parseColor(mTitlebgcolor))//标题背景颜色 Night mode
                .setBgColor(Color.parseColor(mBgcolore))//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();

            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                //                dialogWindow.setGravity(Gravity.CENTER);//在底部显示


            }
        }

        if (pvTime != null) {
            pvTime.show();//弹出时间选择器，传递参数过去，回调的时候则可以绑定此view
        }


//
//        mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                backgroundAlpha(1.0f);
//            }
//        });
//
//        mDialog.setOnShowListener(new DialogInterface.OnShowListener() {
//            @Override
//            public void onShow(DialogInterface dialog) {
//                backgroundAlpha(mShadowColor);
//            }
//        });

    }

    //打开条目选择器
    public void jsmethod_openItemSelect(final UZModuleContext moduleContext) {
        JSONArray mList = moduleContext.optJSONArray("list");
        JSONArray mId = moduleContext.optJSONArray("mId");
        String mHandTextColor = moduleContext.optString("mHandTextColor", "#000000");
        int mHandTextSize = moduleContext.optInt("mHandTextSize", 18);
        boolean mHandTextIsGrivat = moduleContext.optBoolean("mHandTextIsGrivat", false);
        int liftSize = moduleContext.optInt("liftSize", 100);
        int mWith = moduleContext.optInt("mWith", 100);
        int topSize = moduleContext.optInt("topSize", 100);
        String mBottomTextColor = moduleContext.optString("mBottomTextColor", "#000000");
        int mBottomTextSize = moduleContext.optInt("mBottomTextSize", 18);
        int mLineHight = moduleContext.optInt("mLineHight", 30);
        int mHight = moduleContext.optInt("mHight", 30);
        String mHtmlName = moduleContext.optString("mHtmlName", "index");
        boolean mMove = moduleContext.optBoolean("mMove", true);
        //设置上标题的的大小
        mNiceSpinner = new NiceSpinner(mContext, mHandTextColor, mHandTextSize, mHandTextIsGrivat);
        mDataListBeen = new ArrayList<>();
        mDataList = new ArrayList<>();
        mDataListBeen.clear();
        mDataList.clear();
        // System.out.println("mList.length()==="+mList.length());
        if (mList != null || mList.length() != 0) {
            for (int i = 0; i < mList.length(); i++) {
                try {
                    String name = (String) mList.get(i);
                    String id = (String) mId.get(i);
                    mDataList.add(name);
                    mDataListBeen.add(id);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        //设置下拉列表
        int padding = mLineHight - mBottomTextSize;
        mNiceSpinner.attachDataSource(mDataList, padding, padding, mBottomTextSize, mBottomTextColor);
        RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(mWith, mHight);
        //动态添加Spinner
        if (mDataList.size() != 0) {
            params2.setMargins(liftSize, topSize, 0, 0);
            insertViewToCurWindow(mNiceSpinner, params2, mHtmlName, mMove);
        }
        mNiceSpinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < mDataList.size(); i++) {
                    if (position == i) {
                        JSONObject object = new JSONObject();
                        try {
                            object.put("mItemsName", mDataList.get(i) );
                            object.put("mItemsId", mDataListBeen.get(i));
                            moduleContext.success(object, false);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }


    //不联动条目选择器
    public void jsmethod_openNaxiangItemSelect(final UZModuleContext moduleContext) {
        mOutDlade = moduleContext.optBoolean("maskswitch", true);
        mPadding = moduleContext.optDouble("padding", 1.5);
        mTextSize = moduleContext.optInt("textSize", 18);
        mTitleSize = moduleContext.optInt("mTitleSize", 20);
        mTitleText = moduleContext.optString("titleText", "城市选择");
        mCancel = moduleContext.optString("cancel", "取消");
        mSure = moduleContext.optString("sure", "确定");
        mTitlecolor = moduleContext.optString("titlecolor", "#000000");
        mSubmitcolor = moduleContext.optString("submitcolor", "#1919FF");
        mCancelcolor = moduleContext.optString("cancelcolor", "#1919FF");
        mTitlebgcolor = moduleContext.optString("titlebgcolor", "#F5F5F5");
        mBgcolore = moduleContext.optString("bgcolor", "#FFFFFF");
        mDividercolor = moduleContext.optString("dividercolor", "#000000");
        mTextcolorcenter = moduleContext.optString("textcolorcenter", "#000000");
        mShwonNuber = moduleContext.optInt("colnum", 2);

        JSONArray mOneArray = moduleContext.optJSONArray("oneItems");
        JSONArray mTwoArray = moduleContext.optJSONArray("twoItems");
        JSONArray mThreeArray = moduleContext.optJSONArray("threeItems");
        JSONArray mOneArrayId = moduleContext.optJSONArray("oneItemsId");
        JSONArray mTwoArrayId = moduleContext.optJSONArray("twoItemsId");
        JSONArray mThreeArrayId = moduleContext.optJSONArray("threeItemsId");


        final List<String> mOneList = new ArrayList<>();
        final List<String> mOneListId = new ArrayList<>();
        final List<String> mTwoList = new ArrayList<>();
        final List<String> mTwoListId = new ArrayList<>();
        final List<String> mThreeList = new ArrayList<>();
        final List<String> mThreeListId = new ArrayList<>();

        if (mOneArray != null || mOneArray.length() != 0) {
            for (int i = 0; i < mOneArray.length(); i++) {
                try {
                    mOneList.add((String) mOneArray.get(i));
                    mOneListId.add((String) mOneArrayId.get(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        if (mTwoArray != null || mTwoArray.length() != 0) {
            for (int i = 0; i < mTwoArray.length(); i++) {
                try {
                    mTwoList.add((String) mTwoArray.get(i));
                    mTwoListId.add((String) mTwoArrayId.get(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        if (mThreeArray != null || mThreeArray.length() != 0) {
            for (int i = 0; i < mThreeArray.length(); i++) {
                try {
                    mThreeList.add((String) mThreeArray.get(i));
                    mThreeListId.add((String) mThreeArrayId.get(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                OptionsPickerView mPvOptions = new OptionsPickerBuilder(getContext(), new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        String oneName = null;
                        String twoName = null;
                        String threeName = null;
                        if (mShwonNuber == 1) {
                            oneName = mOneList.get(options1);
                        } else if (mShwonNuber == 2) {
                            oneName = mOneList.get(options1);
                            twoName = mTwoList.get(options2);
                        } else if (mShwonNuber == 3) {
                            oneName = mOneList.get(options1);
                            twoName = mTwoList.get(options2);
                            threeName = mThreeList.get(options3);
                        }
                        JSONObject object = new JSONObject();
                        try {
                            object.put("oneName", oneName);
                            object.put("twoName", twoName);
                            object.put("threeName", threeName);
                            object.put("oneId", mOneListId.get(options1));
                            object.put("twoId", mTwoListId.get(options2));
                            object.put("threeId", mThreeListId.get(options3));
                            moduleContext.success(object, true);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                })

                        .setCancelText(mCancel)//取消按钮文字
                        .setSubmitText(mSure)//确认按钮文字
                        .setTitleText(mTitleText)//标题文字
                        .setDividerColor(Color.parseColor(mDividercolor))
                        .setTextColorCenter(Color.parseColor(mTextcolorcenter)) //设置选中项文字颜色
                        .setTitleSize(mTitleSize)//标题文字大小
                        .setOutSideCancelable(mOutDlade)//点击外部是否取消
                        .setContentTextSize(mTextSize)//滚轮文字的大小
                        .setLineSpacingMultiplier((float) mPadding)//设置两线之间的距离
                        .setTitleColor(Color.parseColor(mTitlecolor))//标题文字颜色
                        .setSubmitColor(Color.parseColor(mSubmitcolor))//确定按钮文字颜色
                        .setCancelColor(Color.parseColor(mCancelcolor))//取消按钮文字颜色
                        .setTitleBgColor(Color.parseColor(mTitlebgcolor))//标题背景颜色 Night mode
                        .setBgColor(Color.parseColor(mBgcolore))//滚轮背景颜色 Night mode
                        .build();

                if (mShwonNuber == 1) {
                    mPvOptions.setNPicker(mOneList, null, null);//一级选择器
                } else if (mShwonNuber == 2) {
                    //                    pvOptions.setPicker(mOneList, mTwoList);//二级选择器
                    mPvOptions.setNPicker(mOneList, mTwoList, null);
                } else if (mShwonNuber == 3) {
                    mPvOptions.setNPicker(mOneList, mTwoList, mThreeList);//三级选择器
                }
                mPvOptions.show();
            }
        });

    }
//    /**
//     * 设置popupwindow外面背景透明度
//     * @param bgalpha 透明度  0-1   0-透明   1-不透明
//     */
//    public void backgroundAlpha(float bgalpha) {
//        WindowManager.LayoutParams lp = getContext().getWindow().getAttributes();
//        lp.alpha = bgalpha;
//        getContext().getWindow().setAttributes(lp);
//    }
    /**
     * 打开密码输入框openPassword
     * */
    public void jsmethod_openPassword(final UZModuleContext moduleContext){
        mPassword = "";
        mOutDlade = moduleContext.optBoolean("maskswitch", false);
        int mPassWordLength = moduleContext.optInt("passwordlength", 6);
        //1.创建一个Dialog对象，如果是AlertDialog对象的话，弹出的自定义布局四周会有一些阴影，效果不好
        mDialogPassword = new Dialog(getContext(), R.style.custom_dialog2);
        //去除标题栏
        mDialogPassword.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //2.填充布局
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View dialogView = inflater.inflate(R.layout.paswrod, null);
        //将自定义布局设置进去
        mDialogPassword.setContentView(dialogView);
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = mDialogPassword.getWindow();
        lp.copyFrom(window.getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.BOTTOM;
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialogPassword.show();
        window.setAttributes(lp);

//        //设置点击其它地方不让消失弹窗
//        mDialogPassword.setCancelable(true);
        final JSONObject object = new JSONObject();
        //点击取消
        dialogView.findViewById(R.id.passcacel).setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  mDialogPassword.dismiss();
                  try {
                      object.put("cancelpay", 300);
                      moduleContext.success(object, true);
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
              }
          });

        //点击外面是否取消
        dialogView.findViewById(R.id.passwordoutside).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               // mDialogPassword.dismiss();
            }
        });
        mPayPwdEditText=  (PayPwdEditText)dialogView.findViewById(R.id.paypwdedittext);
        mPayPwdEditText.initStyle(R.drawable.edit_num_bg, mPassWordLength, 1.0f, R.color.passwordline, R.color.pickerview_topbar_title, 20);
        mPayPwdEditText.setOnTextFinishListener(new PayPwdEditText.OnTextFinishListener() {
            @Override
            public void onFinish(String str) {//密码输入完后的回调
                          mPassword= str;
                           if (mPassword.length()==6){
                               try {
                                   object.put("sixpassword", mPassword);
                                   moduleContext.success(object, false);
                               } catch (JSONException e) {
                                   e.printStackTrace();
                               }
                           }
            }
        });
        //点击确定的
        dialogView.findViewById(R.id.surepay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPassword.length()!=6){
                    Toast.makeText(getContext(),"你输入的密码位数不正确，请核对",Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    object.put("surepassword", mPassword);
                    moduleContext.success(object, false);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void jsmethod_closePassword(final UZModuleContext moduleContext){

        if (mDialogPassword !=null){
            mDialogPassword.dismiss();
        }


    }
}
